/*
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2024-07-26     Tian Yiqing  the first version
 */

#include "drv_common.h"
#include "delay.h"

void rt_hw_us_delay(rt_uint32_t us)
{
    rt_uint32_t ticks;
    rt_uint32_t told, tnow, tcnt = 0;
    rt_uint32_t reload = SysTick->LOAD;

    ticks = us * reload / (1000000 / RT_TICK_PER_SECOND);
    told = SysTick->VAL;
    while (1)
    {
        tnow = SysTick->VAL;
        if (tnow != told)
        {
            if (tnow < told)
            {
                tcnt += told - tnow;
            }
            else
            {
                tcnt += reload - tnow + told;
            }
            told = tnow;
            if (tcnt >= ticks)
            {
                break;
            }
        }
    }
}


uint32_t DecToBcd(uint32_t dec)
{
  uint32_t hBit, lBit, bcd;
  dec = dec % 100;
  hBit = (dec / 10) & 0x0F;
  lBit = (dec % 10) & 0x0F;
  bcd = (hBit << 4) | lBit;
  return bcd;
}

uint32_t BcdToDec(uint32_t bcd)
{
  uint32_t hBit, lBit, dec;
  hBit = (bcd >> 4) & 0x0F;
  lBit = (bcd >> 0) & 0x0F;
  dec = hBit * 10 + lBit;
  return dec;
}

void usb_udelay (const uint32_t usec)
{
    udelay(usec);
}

void usb_mdelay (const uint32_t msec)
{
    mdelay(msec);
}
